package com.scwatch.core.web.back;

import com.scwatch.common.orm.RowSide;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.*;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Backends;
import com.scwatch.core.support.Context;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.scwatch.core.constant.Constants.*;

/**
 *卫视栏目
 * Created by rh005 on 2017/7/17.
 */
@Controller
@RequestMapping("/core/sinatv")
public class SinatvController {
    private static final Logger logger = LoggerFactory
            .getLogger(SinatvController.class);

    /**
     * 卫视查询
     * @param pageable 分页对象
     * @param queryNodeId 栏目
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("list.do")
    @RequiresRoles("super")
    @RequiresPermissions(value = {
            "core:sinatv:list",
            "core:sinatv:list01"
    },logical = Logical.OR)
    public String list(
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            Integer queryNodeId,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        Integer siteId = Context.getCurrentSiteId();
        params.put("EQ_site.id",new  String[]{String.valueOf(siteId)});
        Page<Sinatv> pagedList = sinatvService.findAll(params, pageable);
        modelMap.addAttribute("pagedList", pagedList);
        modelMap.addAttribute("queryNodeId", queryNodeId);
        return "core/sinatv/sinatv_list";
    }

    @RequestMapping("create.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:create")
    public String create(Integer id, org.springframework.ui.Model modelMap) {
        if (id != null) {
            Sinatv bean = sinatvService.get(id);
            modelMap.addAttribute("bean", bean);
        }
        modelMap.addAttribute(OPRT, CREATE);
        return "core/sinatv/sinatv_form";
    }

    @RequestMapping("edit.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:edit")
    public String edit(
            Integer id,
            Integer position,
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Sinatv bean = sinatvService.get(id);
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        RowSide<Sinatv> side = sinatvService.findSide(params, bean, position,
                pageable.getSort());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        modelMap.addAttribute(OPRT, EDIT);
        return "core/sinatv/sinatv_form";
    }

    /**
     * 保存卫视
     * @param bean 卫视对象
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("save.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:save")
    public String save(Sinatv bean, String redirect,
                       HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        bean.setTime(new Date());
        bean.setUser(user);
        sinatvService.save(bean, siteId, user);
        logService.operation("opr.sinatv.add", bean.getName(), null,
                bean.getId(), request);
        logger.info("save Sinatv, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            return "redirect:create.do";
        } else {
            ra.addAttribute("id",bean.getId());
            return "redirect:edit.do";
        }
    }

    /**
     * 修改卫视
     * @param bean 卫视数据对象
     * @param position 数据位置
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("update.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:update")
    public String update(@ModelAttribute("bean") Sinatv bean,
                         Integer position, String redirect, HttpServletRequest request,
                         RedirectAttributes ra) {
        Site site = Context.getCurrentSite();
        Backends.validateDataInSite(bean, site.getId());
        sinatvService.update(bean);
        logService.operation("opr.sinatv.edit", bean.getName(), null,
                bean.getId(), request);
        logger.info("update Sinatv, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }

    /**
     * 删除卫视
     * @param ids 数据id
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("delete.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:delete")
    public String delete(Integer[] ids, HttpServletRequest request,
                         RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
//        PageRequest backpageable=new PageRequest(0,30000,new Sort(Sort.Direction.DESC,"time"));
//        Map<String,String[]> paramMap=new HashMap<String,String[]>();
//        paramMap.put("EQ_site.id",new  String[]{String.valueOf( siteId)});
//        if(ids!=null && ids.length>0){
//           for(int i=0;i<ids.length;i++){
//             Integer id=ids[0];
//             if(id!=null){
//                 paramMap.put("EQ_site.id",new  String[]{String.valueOf( siteId)});
//                 paramMap.put("EQ_sinatv.id",new  String[]{String.valueOf( id)});
//                 Page<Programback> tvpagedList = programBackService.findAll(paramMap, backpageable);
//                 if(tvpagedList.getTotalElements()>0){
//                     ra.addFlashAttribute(MESSAGE, TV_DELETE_REF);
//                     return "redirect:list.do";
//                 }
//             }
//           }
//        }
        Sinatv[] beans = sinatvService.delete(ids);
        for (Sinatv bean : beans) {
            logService.operation("opr.sinatv.delete", bean.getName(),
                    null, bean.getId(), request);
            logger.info("delete Sinatv, name={}.", bean.getName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }

    /**
     * 生成卫视json数据
     * @param nodeId
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("generationTv.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:sinatv:generation:generationTv")
    public String generationTv(Integer nodeId, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Integer[] nodeIds=getNodeIdsByFlag(Constants.MODEL_FLAG_SCTV,siteId);
        if(nodeIds!=null && nodeIds.length>0){
           htmlService.makeNode(nodeIds[0]);
        }
        modelMap.addAttribute(OPRT, CREATE);
        return "redirect:list.do";
    }

    private Integer[] getNodeIdsByFlag(String modelFlag,Integer siteId) {
        Integer [] nodeIds=null;
        Map<String,String[]> paramMap=new HashMap<String,String[]>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        paramMap=new HashMap<String,String[]>();
        String[] idsStr;
        if(models!=null && models.size()>0){
            idsStr=new String[models.size()];
            for(int i=0;i<models.size();i++){
                idsStr[i]=models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id",idsStr);
        }
        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList=nodeQuery.findList(siteId,null,
                null,null,true,
                paramMap, paramSort);
        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];
            for(int i=0;i<currentNodeList.size();i++){
                nodeIds[i]=(currentNodeList.get(i).getId());
            }
        }
        return  nodeIds;
    }


    @ModelAttribute("bean")
    public Sinatv preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? sinatvService.get(oid) : null;
    }

    @Autowired
    private OperationLogService logService;
    @Autowired
    private SinatvService sinatvService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private NodeQueryService nodeQuery;
    @Autowired
    private ProgramBackService programBackService;
}
